<style>
    #user-add {
        padding: 20px 25px 25px 0;
    }
    #user-add .layui-treeSelect .ztree li a, .ztree li span {
        margin: 0 0 2px 3px !important;
    }
</style>
<div class="layui-fluid" id="user-add">
    <form class="layui-form" action="" lay-filter="user-add-form">
        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">用户名：</label>
            <div class="layui-input-block">
                <input type="text" name="username" minlength="2" maxlength="10" lay-verify="range|username"
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机：</label>
            <div class="layui-input-block">
                <input type="tel" name="mobile" lay-verify="phone" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱：</label>
            <div class="layui-input-block">
                <input type="text" name="email" lay-verify="email" maxlength="50" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">学号/工号：</label>
            <div class="layui-input-block">
                <input type="text" name="idNumber" lay-verify="number"  maxlength="50" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">角色：</label>
            <div class="layui-input-block">
                <select name="roleId"
                        lay-verify="required"
                        xm-select-direction="down"
                        xm-select="user-add-role"
                        xm-select-skin="default">
                </select>
            </div>
        </div>



      <!--  <div class="layui-form-item">
            <label class="layui-form-label">部门：</label>
            <div class="layui-input-block">
                <input type="text" name="deptId" id="user-add-dept" class="layui-input">
            </div>
        </div>-->

        <div class="layui-form-item" id="teacher_course">
            <label class="layui-form-label">课程：</label>
            <div class="layui-input-block">
                <input type="text" name="courseName" id="experiment_table" placeholder="请选择实验课程（仅老师用户需要选择）" lay-filter="experiment_table" class="layui-input">
                <input type="hidden" id="courseId">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">班级：</label>
            <div class="layui-input-block">
                <input name="deptId" type="hidden" id="dept_tree">
                <div class="ele1" lay-filter="data1"></div>
            </div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">状态：</label>
            <div class="layui-input-block">
                <input type="radio" name="status" value="1" title="有效" checked="">
                <input type="radio" name="status" value="0" title="禁用">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">性别：</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="0" title="男性">
                <input type="radio" name="sex" value="1" title="女性">
                <input type="radio" name="sex" value="2" title="保密" checked="">
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">个人简介：</label>
            <div class="layui-input-block">
                <textarea name="description" maxlength="100" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item febs-hide">
            <button class="layui-btn" lay-submit="" lay-filter="user-add-form-submit" id="submit"></button>
            <button type="reset" class="layui-btn" id="reset"></button>
        </div>
    </form>
</div>

<script>
    layui.use(['febs', 'form', 'formSelects','eleTree','tableSelect', 'validate', 'treeSelect'], function () {
        var $ = layui.$,
            febs = layui.febs,
            layer = layui.layer,
            formSelects = layui.formSelects,
            treeSelect = layui.treeSelect,
            tableSelect = layui.tableSelect,
            eleTree = layui.eleTree,
            form = layui.form,
            $view = $('#user-add'),
            validate = layui.validate;

        form.verify(validate);
        form.render();

        var _deptTree = eleTree.render({
            elem: '.ele1',
            url: ctx + 'dept/tree',
            accordion: true,
            highlightCurrent: true,
            showCheckbox: true,
            checkStrictly: true,
            renderAfterExpand: false,
            /*   where: {
                   "deptName": $deptName.val().trim(),
                   "invalidate_ie_cache": new Date()
               },*/
            request: {
                name: 'name',
                key: "id",
                checked: "checked",
                data: 'data'
            },
            response: {
                statusName: "code",
                statusCode: 200,
                dataName: "data"
            },
        });

        tableSelect.render({
            elem: '#experiment_table',	//定义输入框input对象 必填
            checkedKey: 'courseName', //表格的唯一建值，非常重要，影响到选中状态 必填
            searchKey: 'courseName',	//搜索输入框的name值 默认keyword
            searchPlaceholder: '请输入实验课程',	//搜索输入框的提示文字 默认关键词搜索
            table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                url: ctx + 'course/select/course',
                cols: [
                    [
                        { type: 'radio' },
                        {field: 'courseId', title: '课程ID', minWidth: 100},
                        {field: 'courseName', title: '课程名称', minWidth: 100},
                        {field: 'deptNameList', title: '班级名称列表', align: 'center', width: 300},
                    ]
                ]
            },
            done: function (elem, data) {
                //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
                //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
                var NEWJSON = [];
                layui.each(data.data, function (index, item) {
                    NEWJSON.push(item.courseName);
                    $("#courseId").val(item.courseId);
                });
                elem.val(NEWJSON.join(","))
            }
        });

        // alert(user.deptIds);
        // _deptTree.setChecked(user.deptIds,true);

        function initUserValue() {
            form.val("user-update-form", {
                "username": user.username,
                "mobile": user.mobile,
                "email": user.email,
                "status": user.status,
                "sex": user.sex,
                "description": user.description
            });
        }




        formSelects.render();

        treeSelect.render({
            elem: $view.find('#user-add-dept'),
            type: 'get',
            data: ctx + 'dept/select/tree',
            placeholder: '请选择',
            search: false
        });

        formSelects.config('user-add-role', {
            searchUrl: ctx + 'role',
            response: {
                statusCode: 200
            },
            beforeSuccess: function (id, url, searchVal, result) {
                var data = result.data;
                var tranData = [];
                for (var i = 0; i < data.length; i++) {
                    tranData.push({
                        name: data[i].roleName,
                        value: data[i].roleId
                    })
                }
                result.data = tranData;
                return result;
            },
            error: function (id, url, searchVal, err) {
                console.error(err);
                febs.alert.error('获取角色列表失败');
            }
        });

        form.on('submit(user-add-form-submit)', function (data) {
            var deptId = _deptTree.getChecked(false, true);
            var dept = [];
            for (var j = 0; j < deptId.length; j++) {
                dept.push(deptId[j].id);
            }

            let roleId = data.field.roleId.split(",");
            var teacher = 0;
            for (var i = 0; i < roleId.length; i++) {
                if (roleId[i] === '82') {
                    teacher = roleId[i];
                }
            }
            //如果是学生，则不允许部门ID有两个值
            if (teacher === '82') {
                if (deptId.length > 1) {
                    febs.alert.warn('警告！学生用户只能有一个班级，请重新选择！');
                    return false;
                }
            }
            data.field.dept = dept;

            alert(data.field.courseName);
            alert(data.field.courseId);
            febs.post(ctx + 'user', data.field, function () {
                layer.closeAll();
                febs.alert.success('新增用户成功，初始密码为 123456');
                $('#febs-user').find('#query').click();
            });
            return false;
        });
    });
</script>